package org.jeecg.modules.flower.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.flower.entity.*;
import org.jeecg.modules.flower.service.IFlowerOutorderinfoDService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.flower.service.IFlowerOutorderinfoService;
import org.jeecg.modules.flower.service.IFlowerStorehouseService;
import org.jeecg.modules.flower.service.IFlowerTagInfoService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 出库单仓库子表
 * @Author: jeecg-boot
 * @Date:   2022-07-15
 * @Version: V1.0
 */
@Api(tags="出库单仓库子表")
@RestController
@RequestMapping("/flower/flowerOutorderinfoD")
@Slf4j
public class FlowerOutorderinfoDController extends JeecgController<FlowerOutorderinfoD, IFlowerOutorderinfoDService> {
	@Autowired
	private IFlowerOutorderinfoDService flowerOutorderinfoDService;
	 @Autowired
	 private IFlowerOutorderinfoService flowerOutorderinfoService;

	 @Autowired
	 private IFlowerStorehouseService flowerStorehouseService;
	 @Autowired
	 private IFlowerTagInfoService flowerTagInfoService;

	 /**
	 * 分页列表查询
	 *
	 * @param flowerOutorderinfoD
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "出库单仓库子表-分页列表查询")
	@ApiOperation(value="出库单仓库子表-分页列表查询", notes="出库单仓库子表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(FlowerOutorderinfoD flowerOutorderinfoD,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<FlowerOutorderinfoD> queryWrapper = QueryGenerator.initQueryWrapper(flowerOutorderinfoD, req.getParameterMap());
		Page<FlowerOutorderinfoD> page = new Page<FlowerOutorderinfoD>(pageNo, 99999);
		IPage<FlowerOutorderinfoD> pageList = flowerOutorderinfoDService.page(page, queryWrapper);
		List<FlowerOutorderinfoD> infoDRecords = pageList.getRecords();

		//拼接该成本中心的所有仓库，及仓库库存！
		FlowerOutorderinfo outorderinfo = flowerOutorderinfoService.getById(flowerOutorderinfoD.getMainid());
		String cost = outorderinfo.getCost();

		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
		QueryWrapper<FlowerTagInfo> tagInfoQueryWrapper = new QueryWrapper<>();
		tagInfoQueryWrapper.select("source_base ,source_greenhouse ,storehouse,cost, variety,variety_code,packing_specifications,flower_pole_length, count(1) as classes ");
		tagInfoQueryWrapper.eq("cost",cost);
		tagInfoQueryWrapper.eq("variety_code",outorderinfo.getVarietyCode());
		tagInfoQueryWrapper.eq("flower_pole_length",outorderinfo.getFlowerPoleLength());
		tagInfoQueryWrapper.eq("packing_specifications",outorderinfo.getPackingSpecifications());
		tagInfoQueryWrapper.eq("state", 1);

		tagInfoQueryWrapper.inSql("storehouse","select b.code from flower_storehouse b , flower_storehouse_detail c where b.id = c.mainid and c.personid = '"+sysUser.getId()+"'");
//		tagInfoQueryWrapper.exists("select 1 from flower_storehouse b , flower_storehouse_detail c where b.id = c.mainid and b.code=storehouse  and c.personid = '"+sysUser.getId()+"'");

		tagInfoQueryWrapper.groupBy("source_base" ,"source_greenhouse" ,"storehouse","cost", "variety","variety_code","packing_specifications","flower_pole_length");
		tagInfoQueryWrapper.orderByAsc("classes");
		tagInfoQueryWrapper.orderByAsc("variety_code");
		Page<FlowerTagInfo> page2 = new Page<FlowerTagInfo>(pageNo, 99999);
		IPage<FlowerTagInfo> taginfoList = flowerTagInfoService.page(page2, tagInfoQueryWrapper);

		if(infoDRecords.size()==0){
			infoDRecords =new ArrayList<>();
		}
		for(FlowerTagInfo tagInfo :taginfoList.getRecords()){
			String storehouse = tagInfo.getStorehouse();
			//循环查找
			int i=0;
			for(FlowerOutorderinfoD outorderinfoD : infoDRecords){
				if(outorderinfoD.getStorehouse().equals(storehouse)){
					i=2;
					outorderinfoD.setStorehouseName(tagInfo.getClasses());//库存
					break;
				}else{
					outorderinfoD.setStorehouseName("0");//库存
				}
			}
			if(i==0){
				FlowerOutorderinfoD innfod=new FlowerOutorderinfoD();
				innfod.setSourceBase(tagInfo.getSourceBase());
				innfod.setSourceGreenhouse(tagInfo.getSourceGreenhouse());
				innfod.setStorehouse(storehouse);
				innfod.setMainid(flowerOutorderinfoD.getMainid());
				innfod.setNumber(BigDecimal.ZERO);
				innfod.setStorehouseName( tagInfo.getClasses());//库存
				infoDRecords.add(innfod);
			}
		}
		pageList.setRecords(infoDRecords);
		return Result.ok(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param flowerOutorderinfoDList
	 * @return
	 */
	@AutoLog(value = "出库单仓库子表-批量添加")
	@ApiOperation(value="出库单仓库子表-批量添加", notes="出库单仓库子表-批量添加")
	@PostMapping(value = "/add2")
	@Transactional(rollbackFor = Exception.class)
	public Result<?> add2(@RequestBody List<FlowerOutorderinfoD> flowerOutorderinfoDList) {
		if(flowerOutorderinfoDList.size()==0){
			throw new RuntimeException("请先添加一条仓库数据！");
		}
		List<FlowerOutorderinfoD> flowerOutorderinfoDListNew = new ArrayList<>();

		String mainid = flowerOutorderinfoDList.get(0).getMainid();
		LambdaQueryWrapper<FlowerOutorderinfoD> queryWrapper =new LambdaQueryWrapper<>();
		queryWrapper.eq(FlowerOutorderinfoD::getMainid,mainid);
		flowerOutorderinfoDService.remove(queryWrapper);//删除旧数据

		BigDecimal sumNew = BigDecimal.ZERO;
		BigDecimal sumTotalprice = new BigDecimal(0);
		//校验数据是否大于子表的总数量
		for(FlowerOutorderinfoD flowerOutorderinfoD :flowerOutorderinfoDList){
			if(flowerOutorderinfoD.getNumber()==null || flowerOutorderinfoD.getNumber().compareTo(BigDecimal.ZERO)==0 || "".equals(flowerOutorderinfoD.getNumber())){//数量为0的不保存

			}else {
				sumNew =sumNew.add(flowerOutorderinfoD.getNumber()) ;
				sumTotalprice = sumTotalprice.add(flowerOutorderinfoD.getTotalprice());
				flowerOutorderinfoDListNew.add(flowerOutorderinfoD);
			}
		}
		QueryWrapper<FlowerOutorderinfo> infoquery = new QueryWrapper<>();
		infoquery.eq("id" , mainid);
		infoquery.select("sum(number) as number,totalprice");
		FlowerOutorderinfo  flowerOutorderinfo = flowerOutorderinfoService.getOne(infoquery);
		BigDecimal number = flowerOutorderinfo.getNumber();
		BigDecimal totalprice = flowerOutorderinfo.getTotalprice();
//		Double sumOrder = Double.parseDouble(number);
		if(sumNew .compareTo( number )>0){
			throw new RuntimeException( " 拆分订单的合计数量不能超过出库单的 数量" + number);
		}
		if(sumTotalprice.compareTo(totalprice) != 0 ){
			throw new RuntimeException( " 拆分订单的合计总价 不等于需要出库的总价" + totalprice);
		}
		flowerOutorderinfoDService.saveOrUpdateBatch(flowerOutorderinfoDListNew);//新增新数据
		return Result.ok("添加成功！");
	}

	 /**
	  *   添加
	  *
	  * @param flowerOutorderinfoD
	  * @return
	  */
	 @AutoLog(value = "出库单仓库子表-添加")
	 @ApiOperation(value="出库单仓库子表-添加", notes="出库单仓库子表-添加")
	 @PostMapping(value = "/add")
	 public Result<?> add(@RequestBody FlowerOutorderinfoD flowerOutorderinfoD) {
		 flowerOutorderinfoDService.save(flowerOutorderinfoD);
		 return Result.ok("添加成功！");
	 }
	
	/**
	 *  编辑
	 *
	 * @param flowerOutorderinfoD
	 * @return
	 */
	@AutoLog(value = "出库单仓库子表-编辑")
	@ApiOperation(value="出库单仓库子表-编辑", notes="出库单仓库子表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody FlowerOutorderinfoD flowerOutorderinfoD) {
		flowerOutorderinfoDService.updateById(flowerOutorderinfoD);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "出库单仓库子表-通过id删除")
	@ApiOperation(value="出库单仓库子表-通过id删除", notes="出库单仓库子表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		flowerOutorderinfoDService.removeById(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "出库单仓库子表-批量删除")
	@ApiOperation(value="出库单仓库子表-批量删除", notes="出库单仓库子表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.flowerOutorderinfoDService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "出库单仓库子表-通过id查询")
	@ApiOperation(value="出库单仓库子表-通过id查询", notes="出库单仓库子表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		FlowerOutorderinfoD flowerOutorderinfoD = flowerOutorderinfoDService.getById(id);
		if(flowerOutorderinfoD==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(flowerOutorderinfoD);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param flowerOutorderinfoD
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, FlowerOutorderinfoD flowerOutorderinfoD) {
        return super.exportXls(request, flowerOutorderinfoD, FlowerOutorderinfoD.class, "出库单仓库子表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, FlowerOutorderinfoD.class);
    }

}
